<?php

namespace App\Http\Controllers\Api\Admin;

use App\Enums\HttpType;
use App\Models\Admin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends BaseController
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        $credentials = [
            'account' => $request->string('account'),
            'password' => $request->string('password'),
        ];
        $admin = Admin::where('account', $credentials['account'])->first();
        if (!$admin) {
            return $this->error('账号不存在', HttpType::FAILED->value);
        }
        if (!Hash::check($credentials['password'], $admin->password)) {
            return $this->error('密码错误', HttpType::FAILED->value);
        }
        $token = $admin->createToken($this->authKey)->plainTextToken;

        return $this->success([
            'id' => $admin->id,
            'avatar' => $admin->avatar,
            'token' => $token,
            'token_type' => 'bearer',
        ]);
    }

    /**
     * 当前登录者信息
     * @param Request $request
     * @return JsonResponse
     */
    public function me(Request $request): JsonResponse
    {
        return $this->success(auth()->user());
    }

    public function logout(): JsonResponse
    {
        if ($user = auth()->user()) {
            // @phpstan-ignore-next-line
            assert($user instanceof Admin);
            $user->currentAccessToken()->delete();
        }
        return $this->success();
    }
}
